package com.tkm.types.extensions

//  为String添加扩展
//  String为isEmail方法的receiver
fun String.isEmail(): Boolean {
    val emailRegex = "^([A-Za-z0-9_\\-\\.])+@([A-Za-z0-9_\\-\\.])+\\.[A-Za-z]{2,4}\$"
    return this.matches(emailRegex.toRegex())
}

fun String.padding(count: Int, char: Char = ' '): String {
    val fix = (1..count).joinToString("") { char.toString() }
    return "$fix$this$fix"
}

class PoorGuy {
    var pocket: Double = 0.0
    private var pocketPrivate = 0.1
}

fun PoorGuy.noMoney() {
    println("$this noMoney")
}

//  定义扩展属性
//  扩展属性没有backing field，只能访问property
var PoorGuy.moneyLeft: Double
    get() {
        return this.pocket
    }
    set(value) {
        //  扩展无法访问private内容
//        this.pocketPrivate = value
        this.pocket = value
    }

interface Guy {
    //  interface中定义的属性页没有backing field
    val moneyLeft: Double
        get() = 0.0
}

//  为interface定义默认实现的扩展
fun Guy.noMoney() {
    println("$this noMoney")
}

fun main() {
    println("111".isEmail())
    println("111@qq.com".isEmail())

    println("Hello".padding(5, '*'))
    println("Kotlin".padding(10))

    
    val poorGuy = PoorGuy()
    poorGuy.noMoney()
    println(poorGuy.moneyLeft)

    //  扩展方法绑定receiver
    val isEmailRef: (String) -> Boolean = String::isEmail
    println(isEmailRef("@hello@"))

    //  扩展方法无需绑定receiver
    val paddingRef: (Int, Char) -> String = "CCCP"::padding
    println(paddingRef(3, '*'))
}
